<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link href="assets/css/map.css" rel="stylesheet">
		<link href="assets/css/leaflet.css" rel="stylesheet">
		<link href="assets/css/leaflet.pm.css" rel="stylesheet">
		<title>leaflet</title>
	</head>

	<body>

		<div id="map"></div>
		<div class="btns" style="text-align: center;margin-top: 20px;">
			<button onclick="enableDraw('marker')">测点</button>
			<button onclick="enableDraw('polygon')">测面</button>
			<button onclick="enableDraw('polyline')">测距</button>
			<button onclick="disableDraw()">取消绘制</button>
			<button onclick="clearDraw()">清除</button>
		</div>

		<script src="assets/js/leaflet.js"></script>
		<script src="assets/js/leaflet.pm.min.js"></script>
		<script>
			let map = L.map("map", {
				zoom: 12,
				maxZoom: 18,
				center: [34.269701076858354, 108.94729614257814],
			});
			L.tileLayer(
				"http://{s}.tile.osm.org/{z}/{x}/{y}.png"
			).addTo(map);
			// 默认测量工具，不用可去除
			map.pm.addControls({
				position: 'topleft',
				drawCircle: false,
			});

			let drawLayer = null
			const layerGroup = new L.FeatureGroup().addTo(map);

			// 监听绘制完成事件
			map.on('pm:create', (e) => {
				const {
					layer,
					shape
				} = e;
				disableDraw(); //取消绘制、绘制初始化
				let markerLayer = null;
				layerGroup.addLayer(layer);
				if (shape === "Polygon") {
					const latlng = layer.getLatLngs()[0];
					console.log('坐标',latlng)
				} else if (shape === "Polyline") {
					const latlng = layer.getLatLngs();
					console.log('坐标',latlng)
				} else {
					const latlng = layer._latlng
					const icon = L.icon({
						iconUrl: 'assets/img/marker_icon.png',
						iconSize: [15, 28],
					});
					markerLayer = L.marker([latlng.lat, latlng.lng], {
						icon: icon
					});
				}
				layerGroup.addLayer(markerLayer);
			});


			// 启动绘制
			function enableDraw(type) {
				if (type === "marker") {
					map.pm.enableDraw('Marker');
				} else if (type === "polyline") {
					map.pm.enableDraw('Polyline');
				} else {
					map.pm.enableDraw('Polygon', {
						templineStyle: {
							color: 'blue', // 绘制完线样式
						},
						hintlineStyle: {
							color: 'red',
							dashArray: [5, 5]
						}, //绘制辅助线样式
					});
				}
			}

			// 取消绘制
			function disableDraw() {
				map.pm.disableDraw();
			}
			// 清除绘制
			function clearDraw() {
				layerGroup.clearLayers();
			}
		</script>
	</body>

</html>